﻿var fs=require('fs');
var path=require('path');

function createLog(info,logPath,log){
	
	var now=new Date();
	var today,nowTime,logInfo;
	
	var year=now.getYear()+1900;
	var month=now.getMonth()+1;
	var date=now.getDate();
	var hours=now.getHours();
	var minutes=now.getMinutes();
	var seconds=now.getSeconds();
	
	today=year+'-'+month+'-'+date;
	nowTime=today+' '+hours+':'+minutes+':'+seconds;
	
	log=logPath+'/'+year+'-'+month+'-'+date+log;
	
	logInfo=nowTime+'  '+info+'\n';
	
	path.exists(log,function(exists){
		if(exists){
			fs.readFile(log,function(err,data){
				if(err){
					console.log('读取文件出错');
					throw err;
				}else{
						logInfo+=data;
						fs.writeFile(log,logInfo,'utf-8',function(err){
						if(err){
							console.log(today+'生成日志出错！');
							throw err;	
						}	
					});
				}
			});
		}else{
				fs.writeFile(log,logInfo,'utf-8',function(err){
					if(err){
						console.log(today+'生成日志出错！');
						throw err;
					}	
				});
		}
	});
	

}

function saveLog(info){

		var logPath='./log';
		var log='.log';
		
		path.exists(logPath,function(exists){
			if(!exists){
				fs.mkdir(logPath,function(err){
						if(err){
							console.log('生成日志文件夹出错！');
							throw err;
						}else{
							createLog(info,logPath,log);	
						}
				});	
			}else{
				createLog(info,logPath,log);	
			}	
		});
}

exports.saveLog=saveLog;